package com.link4a.doms.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.link4a.doms.LicenseGenerator;
import com.link4a.doms.dao.Page;
import com.link4a.doms.dao.handler.LicenseHandler;
import com.link4a.doms.dao.handler.OrderHandler;
import com.link4a.doms.exception.BusinessException;
import com.link4a.doms.model.License;
import com.link4a.doms.model.Order;
import com.link4a.doms.vo.OrderCondition;

@Service
public class OrderService {
	
	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private OrderHandler orderHandler;
	@Autowired
	private LicenseHandler licenseHandler;
	
	@Autowired
	private FreemarkerService templateService;
	@Autowired
	private MailService mailService;
	@Autowired
	private LicenseGenerator generator;

	public Order findById(String id) {
		return orderHandler.findById(id);
	}
	
	public Page<Order> findPage(OrderCondition orderCondition) {
		return orderHandler.findPage(orderCondition);
	}
	
	public void save(Order order) {
		order.setStatus(Order.STATUS_PREPAREING);
		orderHandler.merge(order);
		
//		licenseHandler.deleteByOrder(order.getId());
		licenseHandler.merge(order.getLicenses());
	}
	
	public void setDelivered(String id) throws BusinessException {
		orderHandler.updateStatus(id, Order.STATUS_DELIVERED);
		
		Order order = findById(id);
		
		for (License li : order.getLicenses()) {
			String license = generator.generateLicense(li.getMac(), li.getDriver().getAlgorithm());
			li.setLicense(license);
		}
		
		licenseHandler.deliver(order.getLicenses());
		
		sendEmail(order);
	}
	
	public void sendEmail(Order order) throws BusinessException {
		Map<String, Object> models = new HashMap<String, Object>();
		models.put("order", order);
		models.put("date", new Date());
		try {
			String mailBody = templateService.mergeTemplateIntoString("template/order", models, java.util.Locale.SIMPLIFIED_CHINESE);
			mailService.send(order.getCustomerEmail(), "产品授权", mailBody);
		} catch (Throwable e) {
			log.error("", e);
			throw new BusinessException("发送邮件失败，请检查邮箱是否正确！");
		}
	}
	
	public void delete(String id) throws BusinessException {
		if (Order.STATUS_DELIVERED.equals(findById(id).getStatus())) {
			throw new BusinessException("已发货订单不允许删除");
		}
		
		orderHandler.delete(id);
	}
}